<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     *
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
//        Gateway::sendToClient($client_id, json_encode(array(
//            'type'      => 'init',
//            'client_id' => $client_id
//        )));
    }

   /**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param mixed $message 具体消息
    */
   public static function onMessage($client_id, $message)
   {
       $message = json_decode($message, true);
       $message_type = $message['type'];
       switch($message_type) {
           case 'init':
               // uid
               $uid = $message['id'];
               // 设置session
               $_SESSION = [
                   'username' => $message['username'],
                   'avatar'   => $message['avatar'],
                   'id'       => $uid,
                   'sign'     => $message['sign']
               ];

               // 将当前链接与uid绑定
               Gateway::bindUid($client_id, $uid);
               // 通知当前客户端初始化
               $init_message = array(
                   'message_type' => 'init',
                   'id'           => $uid,
               );
               Gateway::sendToClient($client_id, json_encode($init_message));
               break;

           case 'addGroup':
               //入库后追加到主面板
               $client_id = Gateway::getClientIdByUid($message['join_id']);
               Gateway::joinGroup($client_id[0], $message['id']); // 将该用户加入群组
               $add_message = [
                   'type' => 'addGroup',
                   'data' => [
                       'type'      => 'group',
                       'avatar'    => $message['avatar'],
                       'id'        => $message['id'],
                       'groupname' => $message['groupname']
                   ]
               ];
               Gateway::sendToUid($message['join_id'], json_encode($add_message));
               return json_encode(['code' => 0, 'msg' => 'success']);
               break;
           case 'chatMessage':
               // 聊天消息
               $type = $message['data']['to']['type'];
               $to_id = $message['data']['to']['id'];
               $uid = $message['data']['mine']['id'];

               $chat_message = [
                   'message_type' => 'chatMessage',
                   'data' => [
                       'username' => $message['data']['mine']['username'],
                       'avatar'   => $message['data']['mine']['avatar'],
                       'id'       => $type === 'friend' ? $uid : $to_id,
                       'type'     => $type,
                       'content'  => htmlspecialchars($message['data']['mine']['content']),
                       'timestamp'=> time()*1000,
                   ]
               ];
               //聊天记录数组
               $param = [
                   'fromid' => $uid,
                   'toid' => $to_id,
                   'fromname' => $message['data']['mine']['username'],
                   'fromavatar' => $message['data']['mine']['avatar'],
                   'content' => htmlspecialchars($message['data']['mine']['content']),
                   'timeline' => time(),
                   'needsend' => 0
               ];
               switch ($type) {
                   // 私聊
                   case 'friend':
//                       // 插入
//                       $param['type'] = 'friend';
//                       if( empty(Gateway::getClientIdByUid( $to_id ) )){
//                           $param['needsend'] = 1;  //用户不在线,标记此消息推送
//                       }
                       return Gateway::sendToUid($to_id, json_encode($chat_message));
                   // 群聊
                   case 'group':
//                       $param['type'] = 'group';
                       return Gateway::sendToGroup($to_id, json_encode($chat_message), $client_id);
               }
               break;

       }
        // 向所有人发送
       // Gateway::sendToAll("$client_id said $message\r\n");
   }

   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
   public static function onClose($client_id)
   {
       // 向所有人发送
       GateWay::sendToAll("$client_id logout\r\n");
   }
}
